package com.recruit.wechat.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * JSON序列化
     */

    public RedisSerializer<Object> jackson2JsonRedisSerializer(){
        //使用jackson2JsonRedisSerializer来序列化和反序列化redis 的Value的值
        Jackson2JsonRedisSerializer<Object> serializer=new Jackson2JsonRedisSerializer<Object>(Object.class);

        ObjectMapper mapper=new ObjectMapper();

        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        serializer.setObjectMapper(mapper);

        return  serializer;



    }


    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory){
        //生成一个默认配置,通过config对象即可缓存进行自定义配置
        RedisCacheConfiguration config=RedisCacheConfiguration.defaultCacheConfig();
        config=config
                //设置Key为String的序列化
        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                //设置Value为JSON序列化
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
                //不缓存空值
        .disableCachingNullValues()
                //设置默认的过期时间30分钟
        .entryTtl(Duration.ofMinutes(30L));

        //特殊缓存的应用不同的场景
        Map<String,RedisCacheConfiguration> map=new HashMap();

        map.put("Permission",config.entryTtl(Duration.ofMinutes(50L)));//过期时间为5分钟

        //使用自定义的缓存配置初始化一个Redis
        RedisCacheManager cacheManager=RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)//默认配置
                .withInitialCacheConfigurations(map)//特殊缓存
                .transactionAware()//事务
                .build();


        return  cacheManager;
    }


}
